package com.mqb.n4;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * @author mqb
 * @date 2021/4/19 21:36
 */
@Slf4j(topic = "c.ExerciseTransfer")
public class ExerciseTransfer {

    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAmount());
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAmount());
            }
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        // 查看转账后最后总金额
        //log.debug("total {}", a.getMoney() + b.getMoney());
    }

    // Random 线程安全
    static Random random = new Random();

    public static int randomAmount() {
        return random.nextInt(100) + 1;
    }
}

class Account {
    private int money;

    public Account(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    // this.money 和 target.money 都是共享变量，所以此处在方法上 synchronized 是无效的，因为this和target不是同一个对象，要对类对象加锁
    public void transfer(Account target, int amount) {
        synchronized (Account.class) {      // 效率不好
            if (this.money >= amount) {
                this.setMoney(this.getMoney() - amount);
                target.setMoney(target.getMoney() + amount);
            }
        }
    }
}
